#include "oggrecorder.h"
#include "ui_oggrecorder.h"

OggRecorder::OggRecorder(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::OggRecorder), outputLocationFlag(false)
{
    ui->setupUi(this);
    audioRecorder = new QAudioRecorder(this);
    //check for available audio devices
    ui->deviceComboBox->clear();
    ui->deviceComboBox->addItem(tr("Set Device"), QVariant(QString()));
    foreach (const QString &device, audioRecorder->audioInputs()) {
        ui->deviceComboBox->addItem(device, QVariant(device));
    }

    //Signal and slot connections

    connect(audioRecorder, SIGNAL(durationChanged(qint64)), this,
            SLOT(updateRecordingDuration(qint64)));
    connect(audioRecorder, SIGNAL(stateChanged(QMediaRecorder::State)), this,
            SLOT(updateRecordingState(QMediaRecorder::State)));
    connect(audioRecorder, SIGNAL(error(QMediaRecorder::Error)), this,
            SLOT(showErrorMessage()));
}

OggRecorder::~OggRecorder()
{
    delete ui;
    delete audioRecorder;
}

void OggRecorder::on_actionExit_triggered()
{
    QApplication::quit();
}

void OggRecorder::on_actionAbout_triggered()
{
    QMessageBox::information(this,"Linux Ogg Recorder", "<p><b>A Linux audio recorder using vorbis</b></p>"
                             "<p> Alan Crispin (2013) </p>");
}

void OggRecorder::setOutputFile()
{
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"),
                                QDir::currentPath()+"/untitled.ogg",
                                tr("Audio (*.ogg)"));
    audioRecorder->setOutputLocation(QUrl(fileName));
    outputLocationFlag = true;
}

static QVariant getVariantValue(const QComboBox *box)
{
    int idx = box->currentIndex();
    if (idx == -1)
        return QVariant();

    return box->itemData(idx);
}


void OggRecorder::recordAudioOnOff()
{
    if (audioRecorder->state() == QMediaRecorder::StoppedState) {
        audioRecorder->setAudioInput(getVariantValue(ui->deviceComboBox).toString());

        qDebug()<<"Audio Input = "<<audioRecorder->audioInput();

        if (!outputLocationFlag)
            audioRecorder->setOutputLocation(createAudioFilePath());


        QAudioEncoderSettings audioSettings;
        audioSettings.setCodec("audio/vorbis");
        //audioSettings.setSampleRate(44100);
        audioSettings.setBitRate(96000);
        //audioSettings.setQuality(QMultimedia::EncodingQuality(16000));
        audioSettings.setQuality(QMultimedia::VeryHighQuality);
        audioSettings.setEncodingMode(QMultimedia::ConstantBitRateEncoding);
        //audioSettings.setEncodingMode(QMultimedia::ConstantQualityEncoding);
        QString container ="ogg";
        audioRecorder->setEncodingSettings(audioSettings, QVideoEncoderSettings(), container);
        audioRecorder->record();
    }
    else {
        audioRecorder->stop();
    }
}

void OggRecorder::updateRecordingState(QMediaRecorder::State state)
{
    QString statusMessage;

    switch (state) {
    case QMediaRecorder::RecordingState:
        ui->statusBar->showMessage(tr("Please wait..."));
        ui->recordPushButton->setText(tr("Stop"));

        if (audioRecorder->outputLocation().isEmpty())
            statusMessage = tr("Recording");
        else
            statusMessage = tr("Recording to %1").arg(
                        audioRecorder->outputLocation().toString());
        break;

    case QMediaRecorder::StoppedState:
        ui->recordPushButton->setText(tr("Record"));

        statusMessage = tr("Stopped");
    }

}

void OggRecorder::updateRecordingDuration(qint64 duration)
{
    if (audioRecorder->error() != QMediaRecorder::NoError || duration < 2000)
           return;
    ui->statusBar->showMessage(tr("Recorded %1 sec").arg(duration / 1000));

}

void OggRecorder::showErrorMessage()
{
    ui->statusBar->showMessage(audioRecorder->errorString());
}

QUrl OggRecorder::createAudioFilePath()
{
    QDir outputDir(QDir::rootPath());

        int lastImage = 0;
        int fileCount = 0;
        foreach (const QString &fileName, outputDir.entryList(QStringList(QString("testclip_*")))) {
            int imgNumber = fileName.mid(5, fileName.size() - 9).toInt();
            lastImage = qMax(lastImage, imgNumber);
            if (outputDir.exists(fileName))
                fileCount += 1;
        }
        lastImage += fileCount;
        QUrl location(QDir::toNativeSeparators(outputDir.canonicalPath()
            + QString("/testclip_%1").arg(lastImage + 1, 4, 10, QLatin1Char('0'))));
        return location;
}

void OggRecorder::on_outputPushButton_clicked()
{
    //set output file
     this->setOutputFile();

}

void OggRecorder::on_recordPushButton_clicked()
{
    // record button
    this->recordAudioOnOff();
    //ui->statusBar->showMessage(tr("Please wait..."));

}
